package com.zhihao.domain.strategy.service.rule.chain.impl;

import com.zhihao.domain.strategy.repository.IStrategyRepository;
import com.zhihao.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.zhihao.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.zhihao.types.common.Constants;
import com.zhihao.types.enums.ResponseCode;
import com.zhihao.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Jackson
 * @create 2025/3/12 13:00
 * @description 责任链：黑名单过滤
 */
@Slf4j
@Component("rule_blacklist")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BlacklistLogicChain extends AbstractLogicChain {

    // 用于调用仓储层进行黑名单名单查询
    @Resource
    private IStrategyRepository repository;


    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-黑名单开始 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());
        // 1.查询策略配置的黑名单
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        /*
            执行此方法的必定是BlacklistLogicChain黑名单过滤链，则此黑名单规则肯定是被策略链工厂加载了(即：数据库表中肯定是配置了rule_blacklist)，
                但是strategy_rule表中没有同步配置的话，则会报错的 ruleValue.split()会报错 NullPointException
         */
        if (ruleValue == null) {
            throw new AppException(ResponseCode.STRATEGY_RULE_BlACKLIST_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_BlACKLIST_IS_NULL.getInfo());
        }
        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        Integer awardId = Integer.parseInt(splitRuleValue[0]);

        // 黑名单检测
        String[] userBlackIds = splitRuleValue[1].split(Constants.SPLIT);
        for (String userBlackId : userBlackIds) {
            if (userId.equals(userBlackId)) {
                log.info("抽奖责任链-黑名单接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
                // 返回被黑名单拦截的行为信号(key即为为黑名单用户准备的低级奖励)
                return DefaultChainFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .logicModel(ruleModel())
                        // 写入默认配置黑名单奖品值 0.01 ~ 1 积分，也可以配置到数据库表中
                        .awardRuleValue("0.01,1")
                        .build();
            }
        }

        // 继续 过滤后续责任链
        log.info("抽奖责任链-黑名单放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }

}
